<template>
  <van-list
  class="search-result"
  v-model:loading="loading"
  :finished="finished"
  finished-text="没有更多了"
  v-model:error='error'
  error-text="加载失败，请点击重试"
  @load="onLoad"
>
  <van-cell v-for="item in list" :key="item.art_id" :title="item.title" :to='`/article/${item.art_id}`'/>
</van-list>

</template>

<script>
import { ref } from 'vue'
import { getSearchResult } from '@/api/search'
export default {
  name: 'SearchResult',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  setup (props) {
    const list = ref([])
    const loading = ref(false)
    const finished = ref(false)
    const error = ref(false)
    const page = ref(1)
    const onLoad = async () => {
      // 异步更新数据
      try {
        const { data } = await getSearchResult({
          page: page.value, // 页码
          per_page: 20, // 每页数量
          q: props.searchText // 查询关键词
        })
        const { results } = data.data
        list.value.push(...results)
        loading.value = false
        if (results.length) {
          page.value++
        } else {
          finished.value = true
        }
      } catch (err) {
        error.value = true
        loading.value = false
      }
    }

    return {
      list,
      onLoad,
      loading,
      finished,
      error
    }
  }
}
</script>

<style lang='less' scoped>

</style>
